package com.heima.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.dtos.LoginDto;
import com.heima.model.dtos.ResponseResult;
import com.heima.model.enums.AppHttpCodeEnum;
import com.heima.model.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        //判断是否是登陆还是游客
        if (StringUtils.hasText(dto.getPhone()) && StringUtils.hasText(dto.getPassword())) {
            //查询用户
            ApUser apUser = this.lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone())
                    .one();
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_FOUND);
            }
            String salt = apUser.getSalt();
            String imput = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            if (!imput.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_FOUND);
            }
            //构造数据返回
            JSONObject result = new JSONObject();
            result.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt("");
            apUser.setPassword("");
            result.put("user", apUser);
            return ResponseResult.okResult(result);
        } else {
            //游客登陆
            //构造数据返回
            JSONObject result = new JSONObject();
            result.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(result);
        }
    }
}